# Create your views here.
from django.shortcuts import *
from django.http import *
from django.utils import simplejson
from google.appengine.api import users
from appengine_utilities import sessions
from forms import *
from models import *
from itertools import groupby

def index(request):
    ideas = Idea.get_all()    
    return render_to_response('screen/index.html', 
                              {'ideas' : ideas, 
                               'greeting' : greeting() })

def start(request, idea_key):
    idea = Idea.get_by_key(idea_key)  
    answers = sessions.Session()
    parts = Part.all().filter('number < ', 6).fetch(5)
    for p in parts:
        answers['count%s' % p.number] = 0
        answers['res%s' % p.number] = 0 
        
    return render_to_response('screen/start.html',
                              { 'idea' : idea , 'greeting' : greeting()})
    
def question(request, question_id):
    q = Question.get_by_key(question_id)    
    q.choices = Choice.all().filter('question = ', q.key()).fetch(3)
    q.id = q.key()     
    return render_to_response('screen/question.html', 
                              { 'question' : q })
    
def load_questions(request):
    questions = Question.all().order('part').order('number').fetch(25)
    keys = []
    for q in questions:
        keys.append(str(q.key()))       
    
    return HttpResponse(simplejson.dumps(keys), mimetype='application/json')

def ideas(request):
    user = users.get_current_user()
    ideas = Idea.all().filter('user = ', user).fetch(10)    
    return render_to_response('screen/ideas.html', { 'ideas' : ideas, 'greeting' : greeting() })
        
def add_idea(request):
    if request.method == 'POST':        
        idea_form = IdeaForm(data = request.POST)                
        if idea_form.is_valid():
            idea = idea_form.save(commit = False)
            user = users.get_current_user()
            idea.user = user            
            idea.put()
            Idea.clear_cache()
            return HttpResponseRedirect("/screen/ideas")
    else:      
        idea_form = IdeaForm()
    return render_to_response("screen/add_idea.html", 
                              {'form' : idea_form, 'greeting' : greeting() })
    
def edit_idea(request, idea_key):
    idea = Idea.get_by_key(idea_key)
    if request.method == 'POST':    
        idea_form = IdeaForm(request.POST, instance = idea)
        if idea_form.is_valid():            
            idea = idea_form.save(commit = False)
            user = users.get_current_user()
            idea.user = user            
            idea.put()
            return HttpResponseRedirect("/screen/ideas")
    else:
        idea_form = IdeaForm(instance = idea)
    return render_to_response("screen/add_idea.html", 
                              {'form' : idea_form, 'idea' : idea, 'greeting' : greeting() })
    
def delete_idea(request, idea_key):
    Idea.delete_idea(idea_key)
    return HttpResponseRedirect("/screen/ideas")    
    
def parts(request):
    parts = Part.all().fetch(5)
    return render_to_response('screen/parts.html', { 'greeting' : greeting(), 'parts' : parts })

def questions(request):
    questions = Question.all().order('part').order('number').fetch(25)
    for q in questions:
        q.choices = Choice.all().filter('question = ', q.key()).fetch(3)
        q.id = q.key()
    return render_to_response('screen/questions.html', 
                              { 'greeting' : greeting(), 'questions' : questions })

def greeting():
    user = users.get_current_user()    
    if user:
      greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
                  (user.nickname(), users.create_logout_url("/")))
    else:
      greeting = ("<a href=\"%s\">Sign in or register</a>." %
                  users.create_login_url("/"))
    return greeting


#ajax request for posting answer
def answer(request):
    if request.method == 'POST':
        value = request.POST['choice']              
        part = request.POST['part_id']
        
        answers = sessions.Session()        
        answers['count%s' % part] += 1
        answers['res%s' % part] += int(value)
            
        return HttpResponse(value)
    

def populate(request):
    sess = sessions.Session()    
    a = sess['a']
    return HttpResponse(a)

def finish(request, idea_key):
    user = users.get_current_user()    
    parts = Part.get_all()
    idea = Idea.get_by_key(idea_key)
    error = { }
    if request.method == 'POST':
        ok = True
        assessment = {}
        score = {}     
        comment = {}   
        
        for p in parts:
            k = str(p.key())
            num = str(p.number)
            ka = 'ass_%s' % k
            if ka not in request.POST:
                ok = False
                break
            else:
                assessment[num] = request.POST['ass_%s' % k]
                score[num] = int(request.POST['score_%s' % k])
                comment[num] = request.POST['comment_%s' % k]
        if ok:            
            for p in parts:
                k = str(p.number)
                if comment[k] == '':                 
                    comment[k] = 'No comment'
                pr = PartResult(user = user, part = p, idea = idea, result = score[k], assessment = assessment[k], comment = comment[k])
                pr.put()    
                PartResult.clear_cache()        
            return HttpResponseRedirect("/screen/results/")            
        else:
            error['msg'] = "Please select assesments!"
            
    
    answers = sessions.Session()
    
    overall = 0        
    res = []
    for p in parts:        
        if p.number == 6:
            r = overall
        else:
            r = int(answers['res%s' % p.number])
            
        o = {'part' : p, 'result' : r}        
        overall += r
        res.append(o)
        
    #return HttpResponse(map)
    return render_to_response("screen/finish.html", {
        'results' : res,
        'idea' : idea,
        'error' : error,
        'greeting' : greeting()
    })
def average(val):
    l = list(val)
    return float(sum([x.result for x in l])) / len(l)

def results(request):
    part_results = PartResult.get_all()    
    
    results = [{
               'idea': Idea.get_by_key(key),
               'list': list(val)               
            }
            for key, val in groupby(part_results, lambda b: str(b.idea.key()))]
    
    
    for r in results:        
        r['parts'] = [{
                      'part': key,
                      'result': average(val)}
            for key, val in groupby(r['list'], lambda x: x.part.name)]
        r['total'] = len(r['list']) / 6
    
    return render_to_response('screen/results.html', 
                              { 'greeting' : greeting(), 'results' : results })


def presentations(request):
        
    return render_to_response('screen/presentations.html', 
                              {'greeting' : greeting() })